//
//  FXDelayer.swift
//  FXEvent
//
//  Created by JY_NEW on 2022/3/17.
//

import Foundation

/// 延时器，可指定延时操作，在指定的操作后可刷新重新计时
open class FXDelayer: FXEvent<Void> {
    /// 超时时长，若是启动后改变不会改变当前已经启动的延时时长，需要手动重新计时
    open var timeout: TimeInterval
    /// 操作队列，若是启动后改变队列不会改变当前已经启动的队列，需要手动重新计时
    open var queue: DispatchQueue
    /// 是否重复
    open var repeating: Bool
    /// 当前操作
    private var work: DispatchWorkItem? {
        didSet {
            oldValue?.cancel()
        }
    }
    /// 是否已启动
    open var isStarted: Bool {
        return self.work != nil
    }
    public init(timeout: TimeInterval, queue: DispatchQueue = .main, repeating: Bool = true, action: (() -> Void)? = nil) {
        self.timeout = timeout
        self.queue = queue
        self.repeating = repeating
        self.work = nil
        super.init()
        if let action = action {
            self.addBlock(action)
        }
    }
    /// 开始或重新计时
    open func retime() {
        let work = DispatchWorkItem { [weak self] in
            self?.sendActions()
            if self?.repeating ?? false {
                self?.retime()
            }
        }
        self.work = work
        self.queue.asyncAfter(deadline: .now() + self.timeout, execute: work)
    }
    open func stop() {
        self.work = nil
    }
}
